package socket.bio;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author : garvin
 * @version V1.0
 * @date : 2020年06月24日 14:05
 */
public class SocketClient {

    public static void main(String[] args) {
        int clientNum = 3;
        ExecutorService executorService = new ThreadPoolExecutor(1, clientNum,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        for (int i = 0; i < clientNum; i++) {
            executorService.submit(() -> {
                newClient();
            });
        }
        executorService.shutdown();
    }

    private static void newClient() {
        try {
            Socket socket = new Socket("127.0.0.1", 8080);

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            writer.write("I am client");
            writer.flush();
            socket.shutdownOutput();

            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.println(reader.readLine());

            socket.close();
            writer.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
